package com.glory.wxelectricitypda.activity;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.adapter.PackListAdapter;
import com.glory.wxelectricitypda.base.BaseDialogActivity;
import com.glory.wxelectricitypda.bean.PackBean;
import com.glory.wxelectricitypda.bean.ResponseAfterPackBean;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.bean.ResponseQueryBean;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class TakePartActivity extends BaseDialogActivity {


    public PackListAdapter packListAdapter;
    public String packType = "SmallBoxPackageType";
    @BindView(R.id.etLotId)
    FreeUI_ClearEditText etLotId;
    @BindView(R.id.rvThingList)
    RecyclerView rvThingList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.rbSmallBox)
    RadioButton rbSmallBox;
    @BindView(R.id.rbBox)
    RadioButton rbBox;
    @BindView(R.id.checkAll)
    CheckBox checkAll;
    @BindView(R.id.etUser)
    FreeUI_ClearEditText etUser;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_take_part;
    }

    @Override
    protected void initView() {
        rvThingList.setLayoutManager(new LinearLayoutManager(this));
        rvThingList.setItemAnimator(new DefaultItemAnimator());
        rvThingList.addItemDecoration(new DividerItemDecoration(this, 1));

        packListAdapter = new PackListAdapter(null);
        packListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        packListAdapter.isFirstOnly(true);
        rvThingList.setAdapter(packListAdapter);
    }

    @Override
    protected void initData() {
        checkAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                packListAdapter.setAll(isChecked);
            }
        });

        etLotId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    boolean isHave = false;
                    for (PackBean entity : packListAdapter.getData()) {
                        if (entity.getLOTID().equalsIgnoreCase(s.toString())) {
                            isHave = true;
                            break;
                        }
                    }
                    if (isHave) {
                        showToast("批次号已存在列表中", false);
                    } else {
                        requestLotData(s.toString());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void requestLotData(String lotId) {
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("LOTID", lotId);
            jsonObject1.put("ACTIONTYPE", "CHECKUNPACKLOTINFO");
            jsonObject1.put("PACKAGETYPE", packType);
            jsonObject.put("Data",jsonObject1);
            jsonObject.put("MessageName","EUIT.EUITLOTQUERY");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject,this, new FreeUI_DialogEntityCallBack<ResponseBean<ResponseQueryBean>>(
                new TypeToken<ResponseBean<ResponseQueryBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<ResponseQueryBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    PackBean packBean = response.body().getBody().getLOT();
                    packListAdapter.addData(0,packBean);
                    rvThingList.smoothScrollToPosition(0);
                    etLotId.requestFocus();
                    etLotId.setText("");
                }
            }

            @Override
            public void onError(Response<ResponseBean<ResponseQueryBean>> response) {
                super.onError(response);
                loadError(response.getException(), "拆包查询");
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("拆包");
        freeUI_titleView.setRightListener("拆包", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final List<PackBean> selectList = new ArrayList<>();
                for (PackBean packBean : packListAdapter.getData()) {
                    if (packBean.isSelect()) {
                        selectList.add(packBean);
                    }
                }
                if (selectList.size() == 0) {
                    showToast("请选择要拆包的批次", false);
                    return;
                }
                String userName = etUser.getText().toString();
                if (userName.isEmpty()){
                    showToast("请输入操作人工号",false);
                    return;
                }
                requestUser(userName, new CallBack() {
                    @Override
                    public void success() {
                        JSONObject jsonObject = new JSONObject();
                        JSONObject jsonObject1 = new JSONObject();
                        try {
                            jsonObject1.put("ACTIONTYPE", "UnPack");
                            jsonObject1.put("PACKAGETYPE", packType);
                            JSONArray jsonArray = new JSONArray(new Gson().toJson(selectList));
                            jsonObject1.put("LOTLIST", jsonArray);
                            jsonObject1.put("PACKEDLOTID", "");
                            jsonObject.put("Data",jsonObject1);
                            jsonObject.put("MessageName","EUIT.EUITPACKING");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        NetUtils.requestPostMesForwardUtils(jsonObject, this,new FreeUI_DialogEntityCallBack<ResponseBean<ResponseAfterPackBean>>(
                                new TypeToken<ResponseBean<ResponseQueryBean>>() {
                                }.getType(), getSupportFragmentManager(), this) {
                            @Override
                            public void onSuccess(Response<ResponseBean<ResponseAfterPackBean>> response) {
                                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                    packListAdapter.getData().removeAll(selectList);
                                    packListAdapter.clearPos();
                                    packListAdapter.notifyDataSetChanged();
                                    showToast("拆包成功", true);
                                    etUser.setText("");
                                    checkAll.setChecked(false);
                                }
                            }

                            @Override
                            public void onError(Response<ResponseBean<ResponseAfterPackBean>> response) {
                                super.onError(response);
                                loadError(response.getException(), "拆包请求");
                            }
                        });
                    }

                    @Override
                    public void fail() {
                        showToast("操作人工号验证失败，请重新输入", false);
                    }

                    @Override
                    public void error() {
                        showToast("连接不到服务器，请重试", false);
                    }
                });
            }
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.rbSmallBox, R.id.rbBox})
    public void onViewClicked(View view) {
        boolean isOk = true;
        if (packListAdapter.getData().size() > 0) {
            isOk = false;
            showToast("列表中存在批次信息，不能更换", false);
        }
        switch (view.getId()) {
            case R.id.rbSmallBox:
                if (isOk) {
                    packType = "SmallBoxPackageType";
                } else {
                    rbBox.setChecked(true);
                }
                break;
            case R.id.rbBox:
                if (isOk) {
                    packType = "BoxPackageType";
                } else {
                    rbSmallBox.setChecked(true);
                }
                break;
        }
    }
}
